import { Request, Response } from "express";
import jwt from "jsonwebtoken";
import bcrypt from "bcrypt";
import { User } from "../models/user";

const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key";
const REFRESH_TOKEN_SECRET =
  process.env.REFRESH_TOKEN_SECRET || "your-refresh-secret-key";
const SALT_ROUNDS = 10;

import fs from "fs";
import path from "path";

const USERS_FILE_PATH = path.join(__dirname, "../data/users.json");

// Load users from JSON file
const loadUsers = (): User[] => {
  try {
    const data = fs.readFileSync(USERS_FILE_PATH, "utf-8");
    return JSON.parse(data);
  } catch (error) {
    return [];
  }
};

// Save users to JSON file
const saveUsers = (users: User[]) => {
  fs.writeFileSync(USERS_FILE_PATH, JSON.stringify(users, null, 2), "utf-8");
};

let users = loadUsers();

export const login = async (req: Request, res: Response) => {
  const { username, password } = req.body;
  const users = loadUsers();
  const user = users.find((u) => u.username === username);

  if (!user) {
    return res.status(401).json({ message: "Invalid credentials" });
  }

  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    return res.status(401).json({ message: "Invalid credentials" });
  }

  const accessToken = jwt.sign({ username: user.username }, JWT_SECRET, {
    expiresIn: "15m",
  });
  const refreshToken = jwt.sign(
    { username: user.username },
    REFRESH_TOKEN_SECRET,
    { expiresIn: "7d" }
  );

  res.json({ accessToken, refreshToken, user });
};

export const register = async (req: Request, res: Response) => {
  const { username, password } = req.body;
  const users = loadUsers();

  if (users.some((u) => u.username === username)) {
    return res.status(400).json({ message: "Username already exists" });
  }

  const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS);
  const newUser = { username, password: hashedPassword };
  users.push(newUser);
  saveUsers(users);

  res.status(200).json({ message: "User registered successfully" });
};

export const refreshToken = async (req: Request, res: Response) => {
  console.log("Refreshing access token");
  const { refreshToken } = req.body;

  try {
    const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET) as {
      username: string;
    };

    // Check if user exists
    const users = loadUsers();
    const user = users.find((u) => u.username === decoded.username);
    if (!user) {
      return res.status(401).json({ message: "User not found" });
    }

    const accessToken = jwt.sign({ username: decoded.username }, JWT_SECRET, {
      expiresIn: "15m",
    });

    res.json({ accessToken });
  } catch (error) {
    res.status(401).json({ message: "Invalid refresh token" });
  }
};
